//
//  ViewController.m
//  MobileOffice
//
//  Created by Appel on 16/10/11.
//  Copyright © 2016年 liaoningjujin. All rights reserved. tttt
//

#import "ViewController.h"
#import "HomeViewController.h"
#import "LoginModel.h"

#define LOGIN_API @"Login"
#define TEST @"iosTest"

@interface ViewController ()<UITextFieldDelegate>
{
   // CGFloat _userInfoViewHeight;//登录框高度
    UIView *_backView;//弹出框
    //BOOL _isNeedMove;//视图是否需要移动
    
}
@property (weak, nonatomic) IBOutlet UITextField *userTextField;
@property (weak, nonatomic) IBOutlet UITextField *passWordTextField;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _loginView.layer.cornerRadius=5;
    _loginButton.layer.cornerRadius=5;
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"userName"]) {
        _userTextField.text=[[NSUserDefaults standardUserDefaults]objectForKey:@"userName"];
    }
    //设置键盘类型
    _userTextField.keyboardType=UIKeyboardTypeAlphabet;
    _passWordTextField.keyboardType=UIKeyboardTypeAlphabet;
    _userTextField.delegate=self;
    _passWordTextField.delegate=self;
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
//    [LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
//    //sleep(3);
//    [LZXHelper hideLoadViewWithView:self.view];
//    //[LZXHelper postMessageWithText:@"玩不发生未能放开那我开了妇女为了那份"];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}


- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    /*
     iphone 6:
     中文
     2014-12-31 11:16:23.643 Demo[686:41289] 键盘高度是  258
     2014-12-31 11:16:23.644 Demo[686:41289] 键盘宽度是  375
     英文
     2014-12-31 11:55:21.417 Demo[1102:58972] 键盘高度是  216
     2014-12-31 11:55:21.417 Demo[1102:58972] 键盘宽度是  375
     
     iphone  6 plus：
     英文：
     2014-12-31 11:31:14.669 Demo[928:50593] 键盘高度是  226
     2014-12-31 11:31:14.669 Demo[928:50593] 键盘宽度是  414
     中文：
     2015-01-07 09:22:49.438 Demo[622:14908] 键盘高度是  271
     2015-01-07 09:22:49.439 Demo[622:14908] 键盘宽度是  414
     
     iphone 5 :
     2014-12-31 11:19:36.452 Demo[755:43233] 键盘高度是  216
     2014-12-31 11:19:36.452 Demo[755:43233] 键盘宽度是  320
     
     ipad Air：
     2014-12-31 11:28:32.178 Demo[851:48085] 键盘高度是  264
     2014-12-31 11:28:32.178 Demo[851:48085] 键盘宽度是  768
     
     ipad2 ：
     2014-12-31 11:33:57.258 Demo[1014:53043] 键盘高度是  264
     2014-12-31 11:33:57.258 Demo[1014:53043] 键盘宽度是  768
     */
    
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    CGFloat height = keyboardRect.size.height;
    if (_backView) {
        UIView *prompt=(UIView *)[_backView viewWithTag:101];
        if (IPHONE_HEIGHT-height-prompt.height-20<prompt.y) {
            prompt.y=IPHONE_HEIGHT-height-prompt.height-20;
        }
        return;
    }
    //判断登录框是否需要更改
    //if (_userViewTopHeight.constant+91+40<height+10) {
        [UIView animateWithDuration:0.5 animations:^{
            _userViewTopHeight.constant=height+10-91-40;
        }];
    //}

    // CGFloat width = keyboardRect.size.width;

}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    //获取键盘高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    CGFloat height = keyboardRect.size.height;
    //如果有IP设置框则移除
    if (_backView) {
        UIView *prompt=(UIView *)[self.view viewWithTag:101];
        if (IPHONE_HEIGHT-height-prompt.height-20>prompt.y) {
            prompt.y=IPHONE_HEIGHT+height-prompt.height-20;
        }
        return;
    }
    [UIView animateWithDuration:0.5 animations:^{
//        if (_isNeedMove) {
            _userViewTopHeight.constant=41;
//            _isNeedMove=NO;
//            _userInfoViewHeight=0;
//        }
    }];

}
//取消键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
//登录
- (IBAction)loginClick:(id)sender {
//    HomeViewController *home=[HomeViewController new];
//    UINavigationController *navc=[[UINavigationController alloc]initWithRootViewController:home];
//    [self presentViewController:navc animated:YES completion:nil];
    //判断用户名密码是否为空
    if (_userTextField.text.length==0){
        [LZXHelper postMessageWithText:@"用户名不能为空!" View:self.view];
        return;
    }
    if (_passWordTextField.text.length==0) {
        [LZXHelper postMessageWithText:@"密码不能为空!" View:self.view];
        return;
    }
    [self.view endEditing:YES];
    //请求
    NSDictionary *dict=@{
                         @"password":_passWordTextField.text,
                         @"username":_userTextField.text,
                         @"equipmentId":[LZXHelper getUuidWithKeyChain],
 //                        @"reqStr":@"weaqtfaw"
                         };
//    NSMutableDictionary *dict2=[[NSMutableDictionary alloc]init];
//    [dict2 setObject:dict forKey:@"content"];
//    [dict2 setObject:@"" forKey:@"sessionId"];
    [LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
    
//   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<content>%@</content>",str];
    
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:LOGIN_API soapBody:soap success:^(id responseObject) {
            [LZXHelper hideLoadViewWithView:self.view];
        //登陆成功，保存用户名
            [[NSUserDefaults standardUserDefaults]setObject:_userTextField.text forKey:@"userName"];
            _passWordTextField.text=@"";
        //解析数据并保存用户数据
            LoginModel *model=[[LoginModel alloc]initWithResponse:responseObject];
            if ([model.code isEqualToString:@"200"]) {
                NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
                [defaults setValue:model.sessionId forKey:@"sessionId"];
                [defaults setValue:model.empName forKey:@"empName"];
                [defaults setValue:model.departName forKey:@"departName"];
                [defaults setValue:model.postName forKey:@"postName"];
                //        [defaults setValue:model.AccServerBeginTime forKey:@"AccServerBeginTime"];
                //        [defaults setValue:model.AccServerEndTime forKey:@"AccServerEndTime"];
                [defaults setValue:model.userType forKey:@"userType"];
                [defaults setValue:model.yearVacateReplaceDays forKey:@"yearVacateReplaceDays"];
                [defaults synchronize];
                [LZXHelper postMessageWithText:@"登录成功!" View:self.view];
                HomeViewController *home=[HomeViewController new];
                UINavigationController *navc=[[UINavigationController alloc]initWithRootViewController:home];
                [self presentViewController:navc animated:YES completion:nil];
            }else if([model.code isEqualToString:@"220"]){
                [LZXHelper postMessageWithText:model.msg View:self.view];
            }
    } failure:^(NSError *error) {
        [LZXHelper hideLoadViewWithView:self.view];
    }];

}


//IP设置
- (IBAction)setButtonClick:(id)sender {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    __weak ViewController *mySelf=self;
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"推送服务IP设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [mySelf creatPromptViewWithType:@"first"];
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"设置IP和端口号" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [mySelf creatPromptViewWithType:@"second"];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:action1];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
//重置
- (IBAction)resetButtonClick:(id)sender {
    _userTextField.text=@"";
    _passWordTextField.text=@"";
}

//创建ip设置view
- (void)creatPromptViewWithType:(NSString *)type{
    //背景view铺满全屏，防止用户乱点击
    _backView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)];
    _backView.backgroundColor=[UIColor clearColor];
    [[[UIApplication sharedApplication].delegate window]addSubview:_backView];
    
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)];
    view.backgroundColor=[UIColor blackColor];
    view.alpha=0.4;
    [_backView addSubview:view];
    
    UIView *prompt=[UIView new];
    prompt.backgroundColor=[UIColor whiteColor];
    prompt.tag=101;
    prompt.layer.cornerRadius=5;
    //如果是first则创建第一种view
    if ([type isEqualToString:@"first"]) {
        prompt.frame=CGRectMake(30, IPHONE_HEIGHT/2-90/2, IPHONE_WIDTH-60, 110);
        UITextField *textView=[[UITextField alloc]initWithFrame:CGRectMake(8, 13, prompt.width-16, 40)];
        textView.tag=120;
        textView.placeholder=@"IP";
        textView.text=[LZXHelper getIPStr];
        UILabel *line=[[UILabel alloc]initWithFrame:CGRectMake(textView.x, textView.y+textView.height, textView.width, 1)];
        line.backgroundColor=COLOR_SKYBLUE;
        [prompt addSubview:line];
        [prompt addSubview:textView];
    }else{
        prompt.frame=CGRectMake(30, IPHONE_HEIGHT/2-90/2, IPHONE_WIDTH-60, 160);
        UITextField *textView=[[UITextField alloc]initWithFrame:CGRectMake(8, 13, prompt.width-16, 40)];
        textView.placeholder=@"IP";
        //textView.layer.borderColor=[COLOR_BROWN CGColor];
        textView.layer.borderWidth=1.0;
        textView.delegate=self;
        textView.text=[LZXHelper getIPStr];
        textView.layer.cornerRadius=5;
        textView.tag=121;
        [textView becomeFirstResponder];
        UITextField *textView2=[[UITextField alloc]initWithFrame:CGRectMake(8, 13+textView.y+textView.height, prompt.width-16, 40)];
        textView2.layer.borderColor=[[UIColor lightGrayColor]CGColor];
        textView2.layer.borderWidth=1.0;
        textView2.placeholder=@"Port";
        textView2.tag=122;
        textView2.delegate=self;
        textView2.text=[LZXHelper getPortStr];
        textView2.layer.cornerRadius=5;
//        UILabel *line=[[UILabel alloc]initWithFrame:CGRectMake(textView2.x, textView2.y+textView2.height, textView2.width, 1)];
//        line.backgroundColor=COLOR_SKYBLUE;
//        [prompt addSubview:line];
        [prompt addSubview:textView];
        [prompt addSubview:textView2];
    }
    [_backView addSubview:prompt];
    CGFloat width=(prompt.width-120*2)/3;//button间隙
    //确定button
    UIButton *okButton=[MyControl creatButtonWithFrame:CGRectMake(width, prompt.height-43, 120, 35) target:self sel:@selector(okClick:) tag:110 image:nil title:@"确认"];
    okButton.backgroundColor=COLOR_MIDBLUE;
    okButton.layer.cornerRadius=5;
    [okButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [prompt addSubview:okButton];
    //取消button
    UIButton *cancelButton=[MyControl creatButtonWithFrame:CGRectMake(okButton.x+okButton.width+width, prompt.height-43, 120, 35) target:self sel:@selector(cancelClick:) tag:110 image:nil title:@"取消"];
    cancelButton.layer.cornerRadius=5;
    cancelButton.backgroundColor=COLOR_BROWN;
    [cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [prompt addSubview:cancelButton];
    
}
#pragma mark - textFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    textField.layer.borderColor=[COLOR_BROWN CGColor];
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    textField.layer.borderColor=[[UIColor lightGrayColor]CGColor];
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
//确认buttonClick
- (void)okClick:(UIButton *)btn{
    UIView *prompt=(UIView *)[_backView viewWithTag:101];
    UITextField *textField1=(UITextField *)[prompt viewWithTag:120];
    UITextField *textField2=(UITextField *)[prompt viewWithTag:121];
    UITextField *textField3=(UITextField *)[prompt viewWithTag:122];
    //以tag为122的textField为判断，如果没有则是推送服务id，如果有则是修改ip和端口号
    if (textField3) {
        if (textField2.text.length==0){
            [LZXHelper postMessageWithText:@"IP地址不能为空!" View:self.view];
            return;
        }
        if (textField3.text.length==0) {
            [LZXHelper postMessageWithText:@"端口号不能为空!" View:self.view];
            return;
        }
        [[NSUserDefaults standardUserDefaults] setObject:textField2.text forKey:@"IP"];
        [[NSUserDefaults standardUserDefaults] setObject:textField3.text forKey:@"Port"];
        [LZXHelper postMessageWithText:@"配置成功!" View:[[UIApplication sharedApplication].delegate window]];
        [UIView animateWithDuration:0.2 animations:^{
            [_backView removeFromSuperview];
        } completion:^(BOOL finished) {
            
            _backView=nil;
        }];
    }else{
        if (textField1.text.length==0){
            [LZXHelper postMessageWithText:@"IP地址不能为空!" View:self.view];
            return;
        }
        [[NSUserDefaults standardUserDefaults] setObject:textField1.text forKey:@"IP"];
        [LZXHelper postMessageWithText:@"配置成功!" View:[[UIApplication sharedApplication].delegate window]];
        [UIView animateWithDuration:0.2 animations:^{
            [_backView removeFromSuperview];
        } completion:^(BOOL finished) {
            
            _backView=nil;
        }];
    }
}
//取消click
- (void)cancelClick:(UIButton *)btn{
    if (_backView) {
        [UIView animateWithDuration:0.2 animations:^{
            [_backView removeFromSuperview];
        } completion:^(BOOL finished) {
            
            _backView=nil;
        }];

    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
